package com.yifeng.repo.apm.endpoint.logging.log4j2;

import com.yifeng.repo.apm.endpoint.console.api.model.LogConfTypeEnum;
import com.yifeng.repo.apm.endpoint.sender.LogSenderManager;
import next.fire.spinus.logx.api.model.LevelEnum;
import next.fire.spinus.logx.utils.env.HostManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.composite.CompositeConfiguration;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.LoggingSystemFactory;
import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by daibing on 2022/10/30.
 *
 * Note: copy from org.springframework.boot.logging.log4j2.Log4J2LoggingSystem (spring-boot-2.6.6)
 */
public class EndpointLog4J2LoggingSystem extends Log4J2LoggingSystem {

    private static final String FILE_PROTOCOL = "file";

    private final boolean localDebug = Boolean.parseBoolean(System.getProperty("log.local.debug"));

    public EndpointLog4J2LoggingSystem(ClassLoader classLoader) {
        super(classLoader);
    }

    @Override
    public void beforeInitialize() {
        if (!localDebug) {
            LogSenderManager.startupLogSender();
        }
        super.beforeInitialize();
    }

    @Override
    protected void loadConfiguration(String location, LogFile logFile, List<String> overrides) {
        Assert.notNull(location, "Location must not be null");
        try {
            List<Configuration> configurations = new ArrayList<>();
            LoggerContext context = getLoggerContext();
            configurations.add(load(location, context));
            for (String override : overrides) {
                configurations.add(load(override, context));
            }
            Configuration configuration = (configurations.size() > 1) ? createComposite(configurations)
                    : configurations.iterator().next();
            context.start(configuration);

            if (!localDebug) {
                // 根据日志中心配置重构appender
                refactorAppender(context);
            }
        }
        catch (Exception ex) {
            throw new IllegalStateException("Could not initialize Log4J2 logging from " + location, ex);
        }
    }

    private Configuration load(String location, LoggerContext context) throws IOException {
        URL url = ResourceUtils.getURL(location);
        ConfigurationSource source = getConfigurationSource(url);
        return ConfigurationFactory.getInstance().getConfiguration(context, source);
    }

    private ConfigurationSource getConfigurationSource(URL url) throws IOException {
        InputStream stream = url.openStream();
        if (FILE_PROTOCOL.equals(url.getProtocol())) {
            return new ConfigurationSource(stream, ResourceUtils.getFile(url));
        }
        return new ConfigurationSource(stream, url);
    }

    private CompositeConfiguration createComposite(List<Configuration> configurations) {
        return new CompositeConfiguration(
                configurations.stream().map(AbstractConfiguration.class::cast).collect(Collectors.toList()));
    }

    @Override
    public Runnable getShutdownHandler() {
        return () -> {
            this.getLoggerContext().stop();
            if (!localDebug) {
                LogSenderManager.shutdownSender();
            }
        };
    }

    @Override
    public void cleanUp() {
        super.cleanUp();
        // LogSenderManager.shutdownSender();
    }

    private LoggerContext getLoggerContext() {
        return (LoggerContext) LogManager.getContext(false);
    }

    /**
     * {@link LoggingSystemFactory} that returns {@link Log4J2LoggingSystem} if possible.
     */
    @Order(Ordered.LOWEST_PRECEDENCE - 1)
    public static class Factory implements LoggingSystemFactory {

        private static final boolean PRESENT = ClassUtils
                .isPresent("org.apache.logging.log4j.core.impl.Log4jContextFactory", Log4J2LoggingSystem.Factory.class.getClassLoader());

        @Override
        public LoggingSystem getLoggingSystem(ClassLoader classLoader) {
            if (PRESENT) {
                return new EndpointLog4J2LoggingSystem(classLoader);
            }
            return null;
        }

    }

    /**
     * 根据日志中心配置动态修改appender.
     */
    private void refactorAppender(LoggerContext loggerContext) {
        this.addAppender(loggerContext);
        this.clearAppender(loggerContext);
    }

    private void addAppender(LoggerContext loggerContext) {
        EndpointLog4J2Appender appender = EndpointLog4J2Appender.newBuilder().build();
        appender.start();
        // log4j2需要使用getRootLogger来获取根节点
        loggerContext.getRootLogger().addAppender(appender);
        LogSenderManager.getLogSender(true).directPrintLog(LevelEnum.INFO, "EndpointLog4J2LoggingSystem-loadConfiguration", "add appender: " + appender.getName());
    }

    private void clearAppender(LoggerContext loggerContext) {
        // 检查远程配置
        boolean fileLogEnabled = LogSenderManager.getLogSender(true).isLogEnabled(LogConfTypeEnum.FILE);
        boolean consoleLogEnabled = LogSenderManager.getLogSender(true).isLogEnabled(LogConfTypeEnum.CONSOLE);
        String clearAppend = HostManager.get().getEnvSetting("clear.append");
        boolean clearAppenderEnabled = StringUtils.hasText(clearAppend);
        LogSenderManager.getLogSender(true).directPrintLog(LevelEnum.INFO, "EndpointLog4J2LoggingSystem-clearAppender",
                "fileLogEnabled=" + fileLogEnabled + ", consoleLogEnabled=" + consoleLogEnabled +  ",clearAppenderEnabled=" + clearAppenderEnabled);
        if (fileLogEnabled && consoleLogEnabled && !clearAppenderEnabled) {
            return;
        }

        // 动态关闭日志配置中的file、console，只做关闭，不做打开
        Map<String, Appender> appends = loggerContext.getRootLogger().getAppenders();
        List<Appender> clearAppenderList = new ArrayList<>();
        List<String> clearAppenderNameList = clearAppenderEnabled ? Arrays.asList(clearAppend.split(",")) : Collections.emptyList();
        for (Map.Entry<String, Appender> entry : appends.entrySet()) {
            if (!fileLogEnabled && entry.getValue() instanceof FileAppender) {
                entry.getValue().stop();
                clearAppenderList.add(entry.getValue());
            }
            if (!consoleLogEnabled && entry.getValue() instanceof ConsoleAppender) {
                entry.getValue().stop();
                clearAppenderList.add(entry.getValue());
            }
            if(clearAppenderEnabled && clearAppenderNameList.contains(entry.getKey())) {
                clearAppenderList.add(entry.getValue());
            }
        }
        for (Appender appender : clearAppenderList) {
            loggerContext.getRootLogger().removeAppender(appender);
            LogSenderManager.getLogSender(true).directPrintLog(LevelEnum.INFO, "EndpointLog4J2LoggingSystem-clearAppender", "remove appender: " + appender.getName());
        }
    }

}
